<link rel="stylesheet" type="text/css" href="/${BasePath}/static/chat/font_Icon/iconfont.css">
<link rel="stylesheet" type="text/css" href="/${BasePath}/static/chat/css/chat.css">
<script src="/${BasePath}/static/js/common/sockjs-0.3.min.js"></script>
<div class="chatContainer">
    <div class="chatBtn">
        <i class="iconfont icon-xiaoxi1"></i>
    </div>
    <div class="chat-message-num" id="num">0</div>
    <div class="chatBox" ref="chatBox">
        <div class="chatBox-head">
            <div class="chatBox-head-one">
                <a id="tou">正在连接...</a>
                <div class="chat-close" style="margin: 10px 10px 0 0;font-size: 14px">关闭</div>
            </div>
            <div class="chatBox-head-two">
                <div class="chat-return">返回</div>
                <div class="chat-people">
                    <div class="ChatInfoHead">
                        <img src="" alt="头像"/>
                    </div>
                    <div class="ChatInfoName">这是用户的名字，看看名字到底能有多长</div>
                </div>
                <input type="hidden" name="userId" id="userId" value="0">
                <div class="chat-close">关闭</div>
            </div>
        </div>
        <div class="chatBox-info">
        	<!-- 人员消息列表 -->
            <div class="chatBox-list" ref="chatBoxlist">
                <div class="chat-list-people">
                    <div><img src="/${BasePath}/static/images/userface4.jpg" alt="头像"/></div>
                    <div class="chat-name">
                        <p class="black">聊天室</p>
                        <input type="hidden" value="0">
                    </div>
                    <div class="message-num" id="ltNum">通畅</div>
                </div>
            </div>
            <div class="chatBox-kuang" ref="chatBoxkuang">
                <div class="chatBox-content">
                  	<!--聊天框-->
                    <div class="chatBox-content-demo" id="chatBox-content-demo">
 						<!-- 收到的消息 -->					
                        <div class="clearfloat">
                            <div class="author-name">
                                <small class="chat-date">2017-12-02 14:26:58</small>
                            </div>
                            <div class="left">
                                <div class="chat-avatars"><img src="/${BasePath}/static/chat/img/icon01.png" alt="头像"/></div>
                                <div class="chat-message">
                                    <img src="/${BasePath}/static/chat/img/1.png" alt="">
                                </div>
                            </div>
                        </div>
						<!-- 发出的消息 -->
                        <div class="clearfloat">
                            <div class="author-name">
                                <small class="chat-date">2017-12-02 14:26:58</small>
                            </div>
                            <div class="right">
                                <div class="chat-message black">嗯，适合做壁纸</div>
                                <div class="chat-avatars"><img src="/${BasePath}/static/chat/img/icon02.png" alt="头像"/></div>
                            </div>
                        </div>

                    </div>
                </div>
                <div class="chatBox-send height10PX">
                    <div class="div-textarea black" contenteditable="true"></div>
                    <div class="temp">
                        <button id="chat-biaoqing" class="btn-default-styles">
                            <i class="iconfont icon-biaoqing"></i>
                        </button>
<!--                         <label id="chat-tuxiang" title="发送图片" for="inputImage" class="btn-default-styles">
                            <input type="file" onchange="selectImg(this)" accept="image/jpg,image/jpeg,image/png"
                                   name="file" id="inputImage" class="hidden">
                            <i class="iconfont icon-tuxiang"></i>
                        </label> -->
                        <button id="chat-fasong" class="btn-default-styles">发送
                        </button>
                    </div>
                    <div class="biaoqing-photo">
                        <ul>
                            <li><span class="emoji-picker-image" style="background-position: -9px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -18px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -52px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -86px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -120px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -120px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -120px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -120px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -120px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -120px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -9px -154px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -40px -154px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -71px -154px;"></span></li>
                            <li><span class="emoji-picker-image" style="background-position: -102px -154px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -133px -154px;"></span>
                            </li>
                            <li><span class="emoji-picker-image" style="background-position: -164px -154px;"></span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
function getNowDate(){
	 var date = new Date();
	 var sign1 = "-";
	 var sign2 = ":";
	 var year = date.getFullYear() // 年
	 var month = date.getMonth() + 1; // 月
	 var day  = date.getDate(); // 日
	 var hour = date.getHours(); // 时
	 var minutes = date.getMinutes(); // 分
	 var seconds = date.getSeconds() //秒
	 var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'];
	 var week = weekArr[date.getDay()];
	 // 给一位数数据前面加 “0”
	 if (month >= 1 && month <= 9) {
	  month = "0" + month;
	 }
	 if (day >= 0 && day <= 9) {
	  day = "0" + day;
	 }
	 if (hour >= 0 && hour <= 9) {
	  hour = "0" + hour;
	 }
	 if (minutes >= 0 && minutes <= 9) {
	  minutes = "0" + minutes;
	 }
	 if (seconds >= 0 && seconds <= 9) {
	  seconds = "0" + seconds;
	 }
	 var currentdate = year + sign1 + month + sign1 + day + " " + hour + sign2 + minutes + sign2 + seconds;
	 return currentdate;
	}
$(function() {
	var websocket;
	var userPic;
	var host = window.location.host;
	if(host.indexOf("localhost") == -1){
		host="104.156.246.143:8080"
	}
    if('WebSocket' in window) {
        console.log("此浏览器支持websocket");
        websocket = new WebSocket("ws://"+host+"/${BasePath}/Websocket/${user.id!'0'}");
    } else if('MozWebSocket' in window) {
        alert("此浏览器只支持MozWebSocket");
    } else {
        alert("此浏览器只支持SockJS");
    }
    websocket.onopen = function(evnt) {
        console.log(evnt); 
        $("#tou").html("欢迎进入聊天室!")
     };
    websocket.onmessage = function(evnt) {
		var totalNum = $("#num").html();
		$("#num").html(parseInt(totalNum)+1)
		var pic ="/${BasePath}/static/images/userface4.jpg"
		var showMessage = evnt.data;
		var index = showMessage.indexOf(":")
		var userId = showMessage.substring(0,index)
		var message = showMessage.substring(index+1)
		$.ajax({
			type: 'post',
			url: "/${BasePath}/main/queryPerinfo",
			data: {"userId":userId},
			dataType: 'json',
			async:false, 
			success: function(data){
				if (data.code == "1"){
					pic = data.info.headPortrait
				}
			}
		});	
		var ans = '<div class="clearfloat">'+
						'<div class="author-name">'+
							'<small class="chat-date">'+getNowDate()+'</small>'+
						'</div>'+
						'<div class="left">'+
							'<div class="chat-avatars"><img src='+pic+' alt="头像"/></div>'+
							'<div class="chat-message black">'+
								message+
							'</div>'+
						'</div>'+
					'</div>'
		$(".chatBox-content-demo").append(ans);
		//聊天框默认最底部
		$(document).ready(function () {
			$("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
		});
     };
     websocket.onerror = function(evnt) {};
     websocket.onclose = function(evnt) {
          console.log("与服务器断开了链接!");
          $("#tou").html("与服务器断开了链接!")
     }
     $('#close').bind('click', function() {
          websocket.close();
     });
     $('#send').bind('click', function() {
          send();
     });

/*jquery扩展函数*/
$.extend({sendMsgT:function(message){
	if (websocket != null) {                       
		console.log(message);            
		websocket.send(message);          
	} else {            
		alert('未与服务器链接.');          
	}    
}
});
//获取用户列表
$.ajax({
	type: 'post',
	url: "/${BasePath}/message/getOnlineUserInfo",
	data: {"userId":${user.id!'0'}},
	dataType: 'json',
	async:false, 
	success: function(data){
		if(data.code==1){
			var html = '';
			var resultList = data.resultList;
			for(var i=0;i<resultList.length;i++){
			html = html+'<div class="chat-list-people">'+
							'<div><img src="'+resultList[i].headPortrait+'" alt="头像"/></div>'+
							'<div class="chat-name">'+
								'<p class="black">'+resultList[i].name+'</p>'+
								'<input type="hidden" value="'+resultList[i].userId+'">'+
							'</div>'+
							'<div class="message-num">在线</div>'+
						 '</div>'				        		
			}
			$(".chatBox-list").append(html);
		}
	}
});
/* 获取当前用户头像 */
$.ajax({
	type: 'post',
	url: "/${BasePath}/main/queryPerinfo",
	data: {"userId":${user.id!'0'}},
	dataType: 'json',
	async:false, 
	success: function(data){
		if (data.code == "1"){
			userPic = data.info.headPortrait
		}
	}
});	

//发送信息
$("#chat-fasong").click(function () {
    var textContent = $(".div-textarea").html().replace(/[\n\r]/g, '<br>')
    if (textContent != "") {
        $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
            "<div class=\"author-name\"><small class=\"chat-date\">"+getNowDate()+"</small> </div> " +
            "<div class=\"right\"> <div class=\"chat-message black\"> " + textContent + " </div> " +
            "<div class=\"chat-avatars\"><img src=\""+userPic+"\" alt=\"头像\" /></div> </div> </div>");
        //发送后清空输入框
        $(".div-textarea").html("");
        //聊天框默认最底部
        $(document).ready(function () {
            $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
        });
        sendMsg(textContent);
    }
});

//      发送表情
$("#chat-biaoqing").click(function () {
    $(".biaoqing-photo").toggle();
});
$(document).click(function () {
    $(".biaoqing-photo").css("display", "none");
});
$("#chat-biaoqing").click(function (event) {
    event.stopPropagation();//阻止事件
});

$(".emoji-picker-image").each(function () {
    $(this).click(function () {
        var bq = $(this).parent().html();
        console.log(bq)
        $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
            "<div class=\"author-name\"><small class=\"chat-date\">"+getNowDate()+"</small> </div> " +
            "<div class=\"right\"> <div class=\"chat-message\"> " + bq + " </div> " +
            "<div class=\"chat-avatars\"><img src=\""+userPic+"\" alt=\"头像\" /></div> </div> </div>");
        //发送后关闭表情框
        $(".biaoqing-photo").toggle();
        //聊天框默认最底部
        $(document).ready(function () {
            $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
        });
        sendMsg(bq);
    })
});


function sendMsgAll(message) {          
    if (websocket != null) {                       
            console.log(message);            
            websocket.send(message);          
    } else {            
    	alert('未与服务器链接.');          
    }        
}

function sendMsg(message){
	/* 发送消息 */
	var tuserId = $("#userId").val();
	if(tuserId!=0){
	    $.ajax({
	        type: 'post',
	        url: "/${BasePath}/message/sengToUser",
	        data: {"fuserId":${user.id!'0'},"tuserId":tuserId,"message":message},
	        dataType: 'json',
	        async:false, 
	        success: function(data){
	        	
	        }

	    });	
	}else{
		sendMsgAll(message)
	}

}

//进聊天页面
$(".chat-list-people").each(function () {
    $(this).click(function () {
        var n = $(this).index();
        $(".chatBox-head-one").toggle();
        $(".chatBox-head-two").toggle();
        $(".chatBox-list").fadeToggle();
        $(".chatBox-kuang").fadeToggle();

        //传名字
        $(".ChatInfoName").text($(this).children(".chat-name").children("p").eq(0).html());

        //传头像
        var sendPic = $(this).children().eq(0).children("img").attr("src");
        $(".ChatInfoHead>img").attr("src", sendPic);
        
        //传id
        var id = $(this).children(".chat-name").children("input").eq(0).val();
        $("#userId").val(id);
        
        //清空之前数据
        $(".chatBox-content-demo").html("");
        //获取历史聊天记录
        if($(this).children(".chat-name").children("input").eq(0).val()!=0){
    		$.ajax({
    			type: 'post',
    			url: "/${BasePath}/message/getMsgList",
    			data: {"sendId":${user.id!'0'},"toUserid":id},
    			dataType: 'json',
    			async:false, 
    			success: function(data){
    				if (data.code == "0"){
    					var msgList = data.data;
    					var html="";
    					for(var i=0;i<msgList.length;i++){
    						if(msgList[i].sendId==id){
			    	           html = '<div class="clearfloat">'+
				                                '<div class="author-name">'+
				                                    '<small class="chat-date">'+msgList[i].createDate+'</small>'+
				                                '</div>'+
				                                '<div class="left">'+
				                                    '<div class="chat-avatars"><img src="'+sendPic+'" alt="头像"/></div>'+
				                                    '<div class="chat-message">'+msgList[i].msgContent+'</div>'+
				                                '</div>'+
			                                '</div>'+html   							
    						}else{
    							html ='<div class="clearfloat">'+
					                                '<div class="author-name">'+
					                                    '<small class="chat-date">'+msgList[i].createDate+'</small>'+
					                                '</div>'+
					                                '<div class="right">'+
					                                    '<div class="chat-message black">'+msgList[i].msgContent+'</div>'+
					                                    '<div class="chat-avatars"><img src="'+userPic+'" alt="头像"/></div>'+
					                                '</div>'+
					                           '</div> '+html    							
    						}
    						
    						
    						
    					}
    					$(".chatBox-content-demo").append(html);
    				}
    			}
    		});	        	
        }

        //聊天框默认最底部
        $(document).ready(function () {
            $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
        });
    })
});

});

function screenFuc() {
    var topHeight = $(".chatBox-head").innerHeight();//聊天头部高度
    //屏幕小于768px时候,布局change
    var winWidth = $(window).innerWidth();
    if (winWidth <= 768) {
        var totalHeight = $(window).height(); //页面整体高度
        $(".chatBox-info").css("height", totalHeight - topHeight);
        var infoHeight = $(".chatBox-info").innerHeight();//聊天头部以下高度
        //中间内容高度
        $(".chatBox-content").css("height", infoHeight - 46);
        $(".chatBox-content-demo").css("height", infoHeight - 46);

        $(".chatBox-list").css("height", totalHeight - topHeight);
        $(".chatBox-kuang").css("height", totalHeight - topHeight);
        $(".div-textarea").css("width", winWidth - 106);
    } else {
        $(".chatBox-info").css("height", 495);
        $(".chatBox-content").css("height", 448);
        $(".chatBox-content-demo").css("height", 448);
        $(".chatBox-list").css("height", 495);
        $(".chatBox-kuang").css("height", 495);
        $(".div-textarea").css("width", 260);
    }
}
(window.onresize = function () {
    screenFuc();
})();
//未读信息数量为空时
var totalNum = $(".chat-message-num").html();
if (totalNum == "") {
    $(".chat-message-num").css("padding", 0);
}
$(".message-num").each(function () {
    var wdNum = $(this).html();
    if (wdNum == "") {
        $(this).css("padding", 0);
    }
});


//打开/关闭聊天框
$(".chatBtn").click(function () {
    $(".chatBox").toggle(10);
    $("#num").html(0)
})
$(".chat-close").click(function () {
    $(".chatBox").toggle(10);
    $("#num").html(0)
})


//返回列表
$(".chat-return").click(function () {
    $(".chatBox-head-one").toggle(1);
    $(".chatBox-head-two").toggle(1);
    $(".chatBox-list").fadeToggle(1);
    $(".chatBox-kuang").fadeToggle(1);
});

//发送图片
function selectImg(pic) {
    if (!pic.files || !pic.files[0]) {
        return;
    }
    var reader = new FileReader();
    reader.onload = function (evt) {
        var images = evt.target.result;
        $.sendMsgT(images);
        $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
            "<div class=\"author-name\"><small class=\"chat-date\">2017-12-02 14:26:58</small> </div> " +
            "<div class=\"right\"> <div class=\"chat-message\"><img src=" + images + "></div> " +
            "<div class=\"chat-avatars\"><img src=\"/${BasePath}/static/chat/img/icon01.png\" alt=\"头像\" /></div> </div> </div>");
        //聊天框默认最底部
        $(document).ready(function () {
            $("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
        });
    };
    reader.readAsDataURL(pic.files[0]);

}


</script>

